package net.dgg.rz.production.service;

import com.alibaba.fastjson.JSONArray;
import net.dgg.framework.tac.utils.DggDateUtil;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.rz.common.base.service.BaseService;
import net.dgg.rz.common.excption.CommonExcption;
import net.dgg.rz.common.service.CommonMangerExtService;
import net.dgg.rz.common.service.CommonService;
import net.dgg.rz.common.utils.SearchUtils;
import net.dgg.rz.common.utils.StringUtils;
import net.dgg.rz.common.utils.ValidateUtils;
import net.dgg.rz.production.dao.*;
import net.dgg.rz.production.entity.*;
import net.dgg.rz.production.entity.dto.ProductOrderDto;
import net.dgg.rz.production.exception.ProductOrderExcption;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class ProductNodeService extends BaseService{
    @Autowired
    private ProductNodeDao productNodeDao;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private CommonMangerExtService commonMangerExtService;
    @Autowired
    private ProductOrderDao productOrderDao;
    @Autowired
    private ProductNodeOperatingDao productNodeOperatingDao;
    @Autowired
    private ProductTimeStatusService productTimeStatusService;
    @Autowired
    private AssistantDao assistantDao;
    @Autowired
    private ProductTimeStatusDao productTimeStatusDao;//超期表
    @Autowired
    private SearchUtils searchUtils;
    @Autowired
    private ProductNodeFlowDao productNodeFlowDao;
    /**
     * <p>@Description 根据流程节点id查询对应小业态所有节点</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/14 0014 17:33 创建时间</p>
     * <p>@return</p>
     */
    public List<ProductNode> queyNodeList(Long nodeFlowId) {
        ValidateUtils.strNotEmpty(nodeFlowId, CommonExcption.class, "节点流程id不能为空!");
        List<ProductNode> nodelist = productNodeDao.query(new HashMap<String, Object>() {{
            put("processId", nodeFlowId);
            put("flag", 1);
        }});
        return nodelist;
    }

    /**
     * <p>@Description 查询一个生产订单流程对应的所有节点加上所有备注节点(详情历史生产备注使用)</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/23 0023 18:50 创建时间</p>
     * <p>@return</p>
     */
    public List<Map> queryNodeAndRemarksNode(Long flowId,ProductOrder productOrder) {
        //查生产订单对应流程的节点
        List<ProductNode> nodelist = this.queyNodeListByFlowIdAndVersion(flowId,productOrder);
//        List<ProductNode> nodelist = this.queyNodeList(flowId);
        List<Map> remarksNodeAllList = new ArrayList<>();
        remarksNodeAllList.add(new HashMap<String, Object>() {{//先把备注加进去
            put("id", "20");
            put("name", "备注");
        }});
        remarksNodeAllList.add(new HashMap<String, Object>() {{//添加其他以便查询其他备注信息
            put("id", "21");
            put("name", "其他");
        }});
        Map<String, Object> remarksNodeMap;
        for (ProductNode node : nodelist) {
            remarksNodeMap = new HashMap<>();
            remarksNodeMap.put("id", node.getId());
            remarksNodeMap.put("name", node.getName());
            remarksNodeAllList.add(remarksNodeMap);
        }
        return remarksNodeAllList;
    }

    /**
     * <p>@Description 详情中的  根据节点的生产备注</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/24 0024 8:41 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void saveProductOperatingByDetail(Map params) {
        UserEntity userEntity = searchUtils.getcurrUser(params);
        ValidateUtils.strNotEmpty(userEntity, CommonExcption.class, "未获取到登陆人信息,请重新登陆！");
        Map userOrg = commonMangerExtService.findOrg(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(userOrg, CommonExcption.class, "未获取到登陆人的部门信息,请重新登陆！");
        ValidateUtils.strNotEmpty(params.get("remark"), CommonExcption.class, "生产备注不能为空！");
        ValidateUtils.strNotEmpty(params.get("productOrderId"), CommonExcption.class, "生产订单ID为空,请刷新页面重试！");
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(Long.valueOf(params.get("productOrderId").toString()));
        Map flowUser = commonMangerExtService.searchUserById(productOrder.getFlowUserId());
        ValidateUtils.isTrue(flowUser.size() != 0, CommonExcption.class, "未获取到当前生产订单流程人员信息,不能备注！");
        Map organizationEntity = commonMangerExtService.findOrg(Long.parseLong(flowUser.get("orgId").toString()));
        ValidateUtils.strNotEmpty(organizationEntity, CommonExcption.class, "未获取到当前生产订单流程人员部门信息！");
        ValidateUtils.strNotEmpty(params.get("nodeId"), CommonExcption.class, "备注节点不能为空！");
        ProductNodeOperating scProductNodeOperating = new ProductNodeOperating();
        scProductNodeOperating.setId(DggKeyWorker.nextId());
        scProductNodeOperating.setRemarksType(2);   //(记录类型  1：节点更新，2：备注)
        scProductNodeOperating.setScProductOrderId(productOrder.getId());
        scProductNodeOperating.setScProductOrderNo(productOrder.getScProductOrderNo());
        scProductNodeOperating.setFlowOrgId(Long.parseLong(organizationEntity.get("id").toString()));
        scProductNodeOperating.setFlowOrgName(organizationEntity.get("name").toString());
        scProductNodeOperating.setFlowUserId(productOrder.getFlowUserId());
        scProductNodeOperating.setFlowUserName(productOrder.getFlowUserName());
        scProductNodeOperating.setOrderStatus(productOrder.getStatus());
        Long nodeId = Long.valueOf(params.get("nodeId").toString());
        scProductNodeOperating.setNodeId(nodeId);
        scProductNodeOperating.setNodeName(params.get("nodeName").toString() + "备注");
        this.saveOpt(scProductNodeOperating, userEntity);
        scProductNodeOperating.setRemark(params.get("remark").toString());
        scProductNodeOperating.setCreaterOrgName(userOrg.get("name").toString());
        productNodeOperatingDao.insert(scProductNodeOperating);
        //更新最新备注时间
        productOrder.setLastRemarkTime(new Date());
        productOrder.setLastRemark(params.get("remark").toString());
        this.updateOpt(productOrder,userEntity);
        productOrderDao.updateByPrimaryKeySelective(productOrder);//更新生产订单
    }

    /**
     * <p>@Description 根据生产id查询协单人员</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/16 0016 16:41 创建时间</p>
     * <p>@return</p>
     */
    public List<Assistant> queyScAssistantList(Long id) {
        ValidateUtils.strNotEmpty(id, CommonExcption.class, "生产订单id不能为空！");
        List<Assistant> scAssistantList = assistantDao.query(new HashMap<String, Object>() {{
            put("scProductOrderId", id);
        }});
        return scAssistantList;
    }
    /**
     * <p>@Description 根据生产订单ID,流程节点ID查详情使用的节点信息</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/20 0020 18:17 创建时间</p>
     * <p>@return</p>
     */
    public List<Map> queryNodeListByProductOrderId(Long productId, Long processId,Long version) {
        ProductOrder order = productOrderDao.selectByPrimaryKey(productId);
        List<Map> maps = new ArrayList<Map>();
        if(StringUtils.isNotEmpty(order.getNodeJson())){
            List<ProductNode> nodelist = JSONArray.parseArray(order.getNodeJson(), ProductNode.class);
            for(ProductNode p: nodelist){
                Map map = new HashMap();
                map.put("name", p.getName());
                map.put("id", p.getId());
                map.put("handleDate", p.getHandleDate());
                map.put("isNaturalorWorkday", p.getIsNaturalorWorkday());
                Map pnoMap = new HashMap();
                pnoMap.put("nodeId",p.getId());
                pnoMap.put("scProductOrderId",order.getId());
                ProductNodeOperating productNodeOperating = productNodeOperatingDao.selectByScOrderIdAndNodeId(pnoMap);
                if(null != productNodeOperating){
                    map.put("createTime", DggDateUtil.format(productNodeOperating.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
                    map.put("createTimeNoFormat", DggDateUtil.format(productNodeOperating.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
                    map.put("nodeOverdueTime", productNodeOperating.getNodeOverdueTime());
                    map.put("nodeTimeStatus", productNodeOperating.getNodeTimeStatus());
                    map.put("nodeEndTime", null == productNodeOperating.getNodeEndTime() ? null: DggDateUtil.format(productNodeOperating.getNodeEndTime(),"yyyy-MM-dd HH:mm:ss"));
                    map.put("createrName", productNodeOperating.getCreaterName());
                }
                maps.add(map);
            }
        }else{
            ProductNodeFlow productNodeFlow=productNodeFlowDao.selectFlowById(new HashMap(){{
                put("flowId", processId);
            }});
            ValidateUtils.strNotEmpty(productNodeFlow, ProductOrderExcption.class, "未查询到对应流程数据");
            Integer old=productNodeFlow.getIsOld();
            if (old==null||old.equals(0)) {
                maps=productNodeDao.queryNodeListByProductOrderIdOld(new HashMap(){{
                    put("productId", productId);
                    put("processId", processId);
                }});

            }else {
                maps = productNodeDao.queryNodeListByProductOrderId(new HashMap<String, Object>() {
                    {
                        put("productId", productId);
                        put("processId", processId);
                        put("version",version);
                    }
                });
            }
        }
        return maps;
    }

    public Long nextNodeOverTime(List<Map> maps,ProductOrder order) {
        List<ProductTimeStatus> productTimeStatusList = productTimeStatusDao.query(new HashMap<String, Object>() {{
            put("id", order.getId());
        }});
        ProductTimeStatus productTimeStatus = null;
        if(productTimeStatusList== null  || productTimeStatusList.size()<1){
           /* throw new ProductOrderExcption("未查询到该主订单生产日期状态");*/
            productTimeStatus = productTimeStatusService.insertProductStatus(order);
        }else{
            //超期表
            productTimeStatus = productTimeStatusList.get(0);
        }

        //接收前超期表中没有节点记录，返回空
        if (StringUtils.isEmpty(productTimeStatus.getNodeId())) {
            return null;
        }
   /*     int i=0;
        for (int j=0;j<maps.size();j++) {
            if (productTimeStatus.getNodeId().equals(maps.get(j).get("id"))&&j+1<maps.size()) {
                i = j + 1;
            }
        }*/
    /*    if (i == 0) {
            return null;
        }*/
//           Map map = maps.get(i);
            if (productTimeStatus.getNodeEndTime().getTime() < System.currentTimeMillis()) {
                return productTimeStatus.getNodeId();
            }else {
                return null;
            }
    }

    /**
     * <p>@Description 根据流程节点id和版本号查询对应流程所有节点</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/14 0014 17:33 创建时间</p>
     * <p>@return</p>
     */
    public List<ProductNode> queyNodeListByFlowIdAndVersion(Long nodeFlowId,ProductOrder productOrder) {
        ValidateUtils.strNotEmpty(nodeFlowId, CommonExcption.class, "节点流程id不能为空!");
        List<ProductNode> maps = new ArrayList<ProductNode>();
        ProductNodeFlow productNodeFlow = productNodeFlowDao.selectFlowById(new HashMap(){{
            put("flowId",nodeFlowId);
        }});
        if(StringUtils.isNotEmpty(productOrder.getNodeJson())){
            maps = JSONArray.parseArray(productOrder.getNodeJson(), ProductNode.class);
        }else{
            Integer old=productNodeFlow.getIsOld();
            if (old==null||old.equals(0)) {
                maps=productNodeDao.queryByFlowId(new HashMap(){{
                    put("flowId", productOrder.getNodeFlowId());
                }});

            }else {
                maps = productNodeDao.queryByFlowIdAndVersion(new HashMap<String, Object>() {
                    {
                        put("flowId", productOrder.getNodeFlowId());
                        put("version",productOrder.getVersion());
                    }
                });
            }
        }

        return maps;
    }

}
